package com.wangsh.userscenter.service.users.api.implay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.userscenter.common.service.BaseServiceImplay;
import com.wangsh.userscenter.common.util.ConstatFinalUtil;
import com.wangsh.userscenter.common.util.PageInfoUtil;
import com.wangsh.userscenter.service.system.api.ISystemService;
import com.wangsh.userscenter.service.system.pojo.ARegion;
import com.wangsh.userscenter.service.users.api.IUsersService;
import com.wangsh.userscenter.service.users.dao.IAAdminsDAO;
import com.wangsh.userscenter.service.users.dao.IAUsersDAO;
import com.wangsh.userscenter.service.users.dao.IAUsersExtendDAO;
import com.wangsh.userscenter.service.users.pojo.AAdmins;
import com.wangsh.userscenter.service.users.pojo.AUsers;
import com.wangsh.userscenter.service.users.pojo.AUsersExtend;

/**
 * 用户的实现类
 * 
 * @author wangshmac
 *
 */
@Service("usersService")
public class UsersServiceImplay extends BaseServiceImplay implements IUsersService
{
	@Autowired
	private IAAdminsDAO adminsDAO;
	@Autowired
	private IAUsersDAO usersDAO;
	@Autowired
	private IAUsersExtendDAO usersExtendDAO;
	
	@Autowired
	private ISystemService systemService;
	
	@Override
	public JSONObject saveOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();
		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", admins.getEmail() + "");
		AAdmins adminRes = this.findOneAdminsService(condMap);
		if (adminRes != null)
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此管理员邮箱已经存在;编号为:" + adminRes.getId());
			return resultJSON;
		}
		int res = this.adminsDAO.save(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "添加失败;影响条数:" + res);
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();

		/*查询用户的单点登陆id是否存在*/
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", admins.getEmail() + "");
		AAdmins adminRes = this.findOneAdminsService(condMap);
		if (adminRes != null && adminRes.getId() != admins.getId())
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此管理员邮箱已经存在;编号为:" + adminRes.getId());
			return resultJSON;
		}

		int res = this.adminsDAO.update(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "更新失败;影响条数:" + res);
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.adminsDAO.delete(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "删除失败;影响条数:" + res);
		}
		return resultJSON;
	}

	@Override
	public List<AAdmins> findCondListAdminsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		List<AAdmins> adminsList = Collections.EMPTY_LIST;
		/* 设置分页相关信息 */
		if(pageInfoUtil != null)
		{
			/* 设置总记录数 */
			condMap.put("totalCountFlag", "true");
			adminsList = this.adminsDAO.findList(condMap);
			if(adminsList.size() == 1)
			{
				AAdmins users = adminsList.get(0);
				pageInfoUtil.setTotalRecord(users.getId());
			}
			
			condMap.put("totalCountFlag", "false");
			condMap.put("currentRecord", pageInfoUtil.getCurrRecord()) ; 
			condMap.put("pageSize", pageInfoUtil.getPageSize());
		}
		adminsList = this.adminsDAO.findList(condMap) ; 
		return adminsList;
	}

	@Override
	public AAdmins findOneAdminsService(Map<String, Object> condMap)
	{
		return this.adminsDAO.findOne(condMap);
	}

	@Override
	public JSONObject saveOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();
		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", users.getEmail() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null)
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此用户员邮箱已经存在;编号为:" + usersRes.getId());
			return resultJSON;
		}
		int res = this.usersDAO.save(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功;影响条数:" + res);
			
			/* 保存用户扩展信息 */
			AUsersExtend usersExtend = users.getUsersExtend()  ;
			if(usersExtend == null)
			{
				usersExtend = new AUsersExtend();
			}
			
			usersExtend.setUsersId(users.getId());
			usersExtend.setCreateTime(new Date());
			usersExtend.setUpdateTime(new Date());
			this.saveOneUsersExtendService(usersExtend);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();

		/*查询用户的单点登陆id是否存在*/
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", users.getEmail() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null && usersRes.getId() != users.getId())
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此用户员邮箱已经存在;编号为:" + usersRes.getId());
			return resultJSON;
		}

		int res = this.usersDAO.update(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功;影响条数:" + res);
			
			/* 更新用户的扩展信息 */
			AUsersExtend usersExtend = users.getUsersExtend() ; 
			if(usersExtend != null)
			{
				this.updateOneUsersExtendService(usersExtend);
			}
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneUsersService(AUsers users, MultipartFile multipartFile) throws Exception
	{
		String websiteUrl = ConstatFinalUtil.SYS_BUNDLE.getString("website.url");
		String uploadFile = ConstatFinalUtil.SYS_BUNDLE.getString("website.uploadFile");
		/* 存储的是网址的绝对路径 */
		String souPath = users.getPhotoPath() ;
		
		String truePath = ConstatFinalUtil.SYS_BUNDLE.getString("website.truePath");
		String fileName = multipartFile.getOriginalFilename() ;
		/* 网站的相对路径 */
		String tarRelaPath = uploadFile + "/users/" + this.dateUtil.formatDate(new Date()) + "/" + UUID.randomUUID().toString() + 
				fileName.substring(fileName.lastIndexOf("."), fileName.length());
		File tarTrueFile = new File(truePath + tarRelaPath);
		/*拼装网址路径*/
		String tarTruePath = websiteUrl + tarRelaPath ;
		
		if(!tarTrueFile.getParentFile().exists())
		{
			tarTrueFile.mkdirs();
		}
		users.setPhotoPath(tarTruePath);
		InputStream is = multipartFile.getInputStream() ;
		FileOutputStream fos = new FileOutputStream(tarTrueFile);
		boolean flag = this.fileUtil.copyFile(multipartFile.getContentType(), is, fos);
		if(flag)
		{
			if(souPath != null && !"".equalsIgnoreCase(souPath))
			{
				/* 相对路径 */
				String relaPath = souPath.substring(souPath.indexOf(uploadFile) + uploadFile.length() , souPath.length());
				File souFile = new File(truePath + relaPath);
				if(!souFile.exists())
				{
					ConstatFinalUtil.SYS_LOG.error("删除原始文件失败:原始文件路径:{}",souFile.getAbsolutePath());
				}
			}
		}
		
		/* 先更新用户的信息 */
		JSONObject dbJSON = this.updateOneUsersService(users);
		return dbJSON;
	}

	@Override
	public JSONObject deleteOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersDAO.delete(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	@Override
	public AUsers findOneUsersService(Map<String, Object> condMap)
	{
		AUsers users = this.usersDAO.findOne(condMap);
		/* 是否查询扩展信息 */
		if("true".equalsIgnoreCase(condMap.get("extend") + ""))
		{
			/* 查询地区 */
			Map<String, Object> extMap = new HashMap<String,Object>();
			
			extMap.clear();
			extMap.put("id", users.getRegionId());
			ARegion region = this.systemService.findOneRegionService(extMap);
			users.setRegion(region);
		}
		return users; 
	}

	@Override
	public List<AUsers> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		List<AUsers> usersList = Collections.EMPTY_LIST;
		/* 设置分页相关信息 */
		if(pageInfoUtil != null)
		{
			/* 设置总记录数 */
			condMap.put("totalCountFlag", "true");
			usersList = this.usersDAO.findList(condMap);
			if(usersList.size() == 1)
			{
				AUsers users = usersList.get(0);
				pageInfoUtil.setTotalRecord(users.getId());
			}
			
			condMap.put("totalCountFlag", "false");
			condMap.put("currentRecord", pageInfoUtil.getCurrRecord()) ; 
			condMap.put("pageSize", pageInfoUtil.getPageSize());
		}
		usersList = this.usersDAO.findList(condMap);
		return usersList;
	}
	
	@Override
	public JSONObject saveOneUsersExtendService(AUsersExtend usersExtend)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersExtendDAO.save(usersExtend);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersExtendService(AUsersExtend usersExtend)
	{
		JSONObject resultJSON = new JSONObject();

		int res = this.usersExtendDAO.update(usersExtend);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneUsersExtendService(AUsersExtend usersExtend)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersExtendDAO.delete(usersExtend);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	@Override
	public AUsersExtend findOneUsersExtendService(Map<String, Object> condMap)
	{
		AUsersExtend usersExtend = this.usersExtendDAO.findOne(condMap);
		return usersExtend; 
	}

	@Override
	public List<AUsersExtend> findCondListUsersExtendService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		List<AUsersExtend> usersExtendList = Collections.EMPTY_LIST;
		/* 设置分页相关信息 */
		if(pageInfoUtil != null)
		{
			/* 设置总记录数 */
			condMap.put("totalCountFlag", "true");
			usersExtendList = this.usersExtendDAO.findList(condMap);
			if(usersExtendList.size() == 1)
			{
				AUsersExtend usersExtend = usersExtendList.get(0);
				pageInfoUtil.setTotalRecord(usersExtend.getId());
			}
			
			condMap.put("totalCountFlag", "false");
			condMap.put("currentRecord", pageInfoUtil.getCurrRecord()) ; 
			condMap.put("pageSize", pageInfoUtil.getPageSize());
		}
		usersExtendList = this.usersExtendDAO.findList(condMap);
		return usersExtendList;
	}

	@Override
	public boolean addUsersTicketService(AUsers usersTicket)
	{
		//ConstatFinalUtil.usersTicketJSON.put(usersTicket.getTicketStr(), usersTicket.toJSON()) ;
		/* 默认存储1分钟 */
		this.redisUtil.put(ConstatFinalUtil.REDIS_TICKET_USERS + usersTicket.getTicketStr(), usersTicket.toJSON() + "", 60);
		return true ; 
	}

	@Override
	public JSONObject verifyUsersTicketService(String ticket)
	{
		//ConstatFinalUtil.usersTicketJSON.getJSONObject(ticket);
		String result = this.redisUtil.get(ConstatFinalUtil.REDIS_TICKET_USERS + ticket) + "";
		JSONObject resultJSON = (JSONObject) JSON.parse(result);
		return resultJSON ; 
	}

	@Override
	public boolean addAdminsTicketService(AAdmins adminsTicket)
	{
		//ConstatFinalUtil.adminsTicketJSON.put(adminsTicket.getTicketStr(), adminsTicket.toJSON());
		/* 默认存储1分钟 */
		this.redisUtil.put(ConstatFinalUtil.REDIS_TICKET_ADMINS + adminsTicket.getTicketStr(), adminsTicket.toJSON() + "", 60);
		return true ; 
	}

	@Override
	public JSONObject verifyAdminsTicketService(String ticket)
	{
		//return ConstatFinalUtil.adminsTicketJSON.getJSONObject(ticket);
		String result = this.redisUtil.get(ConstatFinalUtil.REDIS_TICKET_ADMINS + ticket) + ""; 
		JSONObject resultJSON = (JSONObject) JSON.parse(result);
		return resultJSON ;
	}
}
